//绘制箭头方法
const drawArrow = (fromX, fromY, toX, toY, theta, headlen) => {
  theta = typeof theta != "undefined" ? theta : 30
  headlen = typeof theta != "undefined" ? headlen : 10
  // 计算各角度和对应的P2,P3坐标
  let angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
    angle1 = (angle + theta) * Math.PI / 180,
    angle2 = (angle - theta) * Math.PI / 180,
    topX = headlen * Math.cos(angle1),
    topY = headlen * Math.sin(angle1),
    botX = headlen * Math.cos(angle2),
    botY = headlen * Math.sin(angle2)
  let arrowX = fromX - topX,
    arrowY = fromY - topY
  let path = " M " + fromX + " " + fromY
  path += " L " + toX + " " + toY
  arrowX = toX + topX
  arrowY = toY + topY
  path += " M " + arrowX + " " + arrowY
  path += " L " + toX + " " + toY
  arrowX = toX + botX
  arrowY = toY + botY
  path += " L " + arrowX + " " + arrowY
  return path
}

//坐标转换
const transformMouse = (mouseX, mouseY) => {
  return { x: mouseX, y: mouseY }
}

// 文件下载
const download = (url, filename) => {
  return fetch(url).then(res => res.blob().then(blob => {
    let a = document.createElement('a')
    let url = window.URL.createObjectURL(blob)
    a.href = url
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(url)
  }))
}

// 获取画布图片url
const getImgUrl = () => {
  const ele = document.getElementById('c')
  const url = ele.toDataURL('image/png')
  return url
}

// 本地选择的blob图片转base64图片
const blobToBase64 = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      resolve(reader.result)
    }
    reader.onerror = () => {
      reject(new Error('文件转换失败'))
    }
    reader.readAsDataURL(blob)
  })
}

// localStorage操作
const STORAGE_FABRIC_KEY = 'STORAGE_FABRIC_KEY'
const setStorage = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value))
}
const getStorage = (key) => {
  return JSON.parse(localStorage.getItem(key) || '{}')
}
const removeStorage = (key) => {
  localStorage.removeItem(key)
}
const updateStorage = (key, value) => {
  const data = getStorage(key)
  setStorage(key, { ...data, ...value })
}
// 删除id对应的数据
const deleteStorage = (key, id) => {
  const data = getStorage(key)
  Reflect.deleteProperty(data, id)
  setStorage(key, data)
}

export {
  drawArrow,
  transformMouse,
  download,
  getImgUrl,

  blobToBase64,

  setStorage,
  getStorage,
  removeStorage,
  updateStorage,
  deleteStorage,
  STORAGE_FABRIC_KEY
}
